﻿@model IEnumerable<Kooboo.CMS.Sites.ABTest.ABSiteRuleItem>
@using Kooboo.CMS.Web.Areas.Sites.Models.DataSources;
@using Kooboo.CMS.Common.Runtime;
@{
    Layout = ViewBag.Layout ?? "~/Views/Shared/EditorTemplates/_TR.cshtml";

    var itemJson = Newtonsoft.Json.JsonConvert.SerializeObject(new Kooboo.CMS.Sites.ABTest.ABSiteRuleItem());
    var modelJson = Model != null ? Newtonsoft.Json.JsonConvert.SerializeObject(Model) : "[]";
    var sitesJson = Newtonsoft.Json.JsonConvert.SerializeObject((EngineContext.Current.Resolve<SitesDataSource>()).GetSelectListItems(ViewContext.RequestContext, ""));

}
<table id="siteRuleItems" class="key-value">
    <thead data-bind="visible: data().length>0">
        <tr>
            <th>
                @("Rule name".Localize())
            </th>
            <th>
                @("Site".Localize())
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody data-bind="foreach:{ data:data,afterRender:parseValidation}">
        <tr>
            <td style="width: 180px;">
                <span data-bind="text:RuleItemName"></span>
                <input type="hidden" data-bind="value:RuleItemName, attr: {name: $parent.getPrefixFieldName($index()) + 'RuleItemName'}" />
            </td>
            <td>
                <select class="short" data-bind="value:SiteName,options: Sites, optionsText: 'Text', optionsValue: 'Value',  attr: {name: $parent.getPrefixFieldName($index()) + 'SiteName'}"></select>
                @Html.ValidationMessage("SiteName", new RouteValueDictionary().Merge("data-bind", "attr: {'data-valmsg-for': $parent.getPrefixFieldName($index()) + 'SiteName'}"))
            </td>
            <td></td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td colspan="2">
                @if (!string.IsNullOrEmpty(ViewData.ModelMetadata.Description))
                {
                    <em class="tip">@Html.Raw(ViewData.ModelMetadata.Description.Localize())</em>
                }
            </td>
        </tr>
    </tfoot>
</table>

<script type="text/javascript">
    $(function () {
        function SiteVisitRuleItemsViewModel() {
            var self = this;
            var sites = @Html.Raw(sitesJson);     
            var bindItem = function(item){
                item.Sites = sites;      
            };

            self.data = ko.mapping.fromJS(@Html.Raw(modelJson));

            _.each(self.data(),function(item){
                bindItem(item);
            });
            
            self.addItem = function (obj) {
                var item = ko.mapping.fromJS(_.extend(@Html.Raw(itemJson),obj));
                bindItem(item);  
                self.data.push(item);
            };

            self.removeItem = function () {
                self.data.remove(this);
            };

            var namePrfix = 'Items';
            self.getPrefixFieldName = function (index) {
                return namePrfix + '[' + (index) + '].';
            };

            self.parseValidation = function (element, index, data) {
                $.removeData($('form')[0], 'validator'); //remove validator for the form.
                $.validator.unobtrusive.parse('form');
            };

            var resetRuleItems = function(ruleName,clearItems){
                $.post('@Html.Raw(Url.Action("GetJson", "ABRuleSetting", ViewContext.RequestContext.AllRouteValues()))'
                        ,{uuid:ruleName})
                        .done(function(items){
                            var oldItems = ko.toJS(self.data());
                            self.data.removeAll();                         
                            _.each(items,function(element,index){
                                var item  = {RuleItemName:element.Name};
                                var old = _.first(_.filter(oldItems,function(old){                                           
                                    return item.RuleItemName === old.RuleItemName;
                                }));
                                if (old!=null) {
                                    item = old;
                                }
                                self.addItem(item);
                            });
                        });
            };
            var $ruleName =$('#RuleName');
            $ruleName.change(function(){
                var val = $(this).val();
                resetRuleItems(val);
            });
            resetRuleItems($ruleName.val());
            }
        ko.applyBindings(new SiteVisitRuleItemsViewModel(), $("#siteRuleItems")[0]);
    });
</script>
